/**
 * Created by WLG on 2018/11/9.
 */
//let _ = require('lodash');

let BaseSocketHandler = require("./baseSocketHandler");
let serverConfig = require('../config/serverConfig');
let SystemConst = require("../config/systemConst");
let ChatMsgService = require("../services/chatMsgService");
let SocketPushService = require("../services/socketPushService");
let QueryData = require('../model/sysQueryData');
let ChatMemInfoService = require('../services/chatMemInfoService');

let redisDB = require('../lib/redisManage');

let socketMap = {};
/**
 * 聊天 处理器
 */
class ChatSocketHandler extends BaseSocketHandler {
    static attach(io, socket){
        socket.emit('connected', {});
        /**
         * 接收消息
         * 1.判断重复
         * 2.存消息
         * 3.更新缓存 lastMsg
         * 4.反馈接收成功
         * 5.推送
         */
        socket.on(SystemConst.EventName.ChatMsgSocket.ClientSend,async (data)=>{
            let chatMsg = data.data;
            //判断是否重复消息
            if(await super.checkSocketMsgIdExistAndCacheIt(data.smid)){
            }else{
                chatMsg.serverReceiveTime = (new Date()).getTime();
                let result = await ChatMsgService.save(chatMsg);
                chatMsg._id = result._id;
                let qd = new QueryData();
                qd.data = chatMsg;
                //更新缓存 lastMsg
                //ChatService.updateChatCacheAndDbByChatMsg(chatMsg);
                await ChatMsgService.setLastChatMsgCache(chatMsg.chatID,chatMsg);
                //服务器接收成功
                qd.smid = data.smid;
                socket.emit(SystemConst.EventName.ChatMsgSocket.ServerReceive,qd);
                //推送
                SocketPushService.pushChatMsg(io,chatMsg);
            }
        });
        //接收推送成功
        socket.on(SystemConst.EventName.ChatMsgSocket.ClientReceive,async (data)=> {
            let readData = data.data;
            if( readData.memId && readData.chatId ){
                await ChatMemInfoService.updateChatMemInfoReadState( readData.memId, readData.chatId);
            }
            //console.log("收到了消息推送成功的消息！");
        });
    };
}
module["exports"] = ChatSocketHandler;